from threading import Thread, Lock

g_num = 0
lock = Lock()  # 互斥锁来解决脏数据


# 采用两个线程分别对g_num累加100万次

# def sum_num():
#     lock.acquire()
#     for i in range(1000000):
#         global g_num
#         g_num += 1
#     lock.release()
#     print(f'线程1累加后的结果{g_num}')
#
#
# def sum_num2():
#     lock.acquire()
#     for i in range(1000000):
#         global g_num
#         g_num += 1
#     lock.release()
#     print(f'线程2累加后的结果{g_num}')

def sum_num():
    with lock:
        for i in range(1000000):
            global g_num
            g_num += 1
    print(f'线程1累加后的结果{g_num}')


def sum_num2():
    with lock:
        for i in range(1000000):
            global g_num
            g_num += 1
    print(f'线程2累加后的结果{g_num}')


# 运行之后出现了脏数据
if __name__ == '__main__':
    t1 = Thread(target=sum_num)
    t2 = Thread(target=sum_num2)
    t1.start()
    # t1.join() # 造成主线程阻塞 解决脏数据原因之一

    t2.start()
